//
//  QSSendProblemViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/24.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSSendProblemViewController.h"
#import "QSProblemDetailViewController.h"
#import "QSProblemReportFirstCell.h"
#import "QSProblemReportSecondCell.h"
#import "QSProblemReprotInterface.h"
#import "QSOSSUploadHelper.h"
@interface QSSendProblemViewController ()
@property (nonatomic, strong)UIButton *submitButton;

@property (nonatomic, strong)NSArray *problemTypeArr;

@property (nonatomic, strong)NSArray *townArr;

@property (nonatomic, strong)NSArray *companyArr;

@property (nonatomic, copy)NSString *typeId;
@property (nonatomic, copy)NSString *problemTitle;
@property (nonatomic, copy)NSString *info;
@property (nonatomic, copy)NSString *pic;

@property (nonatomic, copy)NSArray *imageArr;
@property (nonatomic, strong)NSArray *sendPicArr;
@end
static NSString *problemFirstcell = @"ProblemFirstcell";
static NSString *problemSecoundcell = @"ProblemSecoundcell";

@implementation QSSendProblemViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"问题提交";
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavgationBarHeight  - kRealValue(78));
    
    [self.tableView registerNib:[UINib nibWithNibName:@"QSProblemReportFirstCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:problemFirstcell];
    [self.tableView registerNib:[UINib nibWithNibName:@"QSProblemReportSecondCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:problemSecoundcell];
    
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F4"];
    [self configSubView];
    [self getProblemType];
    [self getTownList];
//    [self getCompanyList];
    if (self.signId) {//从签到过来点返回直接返回首页
        UIBarButtonItem *backBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_navigation_back"] target:self action:@selector(handleBackHome:)];
        
        self.navigationItem.leftBarButtonItem = backBtn;
    }
}

- (void)configSubView{
    [self.view addSubview:self.submitButton];
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRealValue(24));
        make.right.equalTo(self.view).offset(- kRealValue(24));
        make.bottom.equalTo(self.view).offset(- kRealValue(24));
        make.height.offset(44);
    }];
}

#pragma mark - 懒加载
- (UIButton *)submitButton{
    if (!_submitButton) {
        _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _submitButton.layer.cornerRadius = 22;
        _submitButton.backgroundColor = [UIColor colorWithHexString:@"#128BEC"];
        [_submitButton setTitle:@"提交问题" forState:UIControlStateNormal];
        [_submitButton setTitleColor:[UIColor QSColorWhiteFFFFFF] forState:UIControlStateNormal];
        _submitButton.titleLabel.font = [UIFont QSFontOfSize16];
        [_submitButton addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitButton;
}

#pragma mark - Action
- (void)submitAction:(UIButton *)sender{
    //提交请求
    if (!self.companyKey) {
        [QSAppKeyWindow showAutoHideHudWithText:@"请选择企业"];
        return;
    }
    
    if (!self.problemTitle) {
        [QSAppKeyWindow showAutoHideHudWithText:@"请输入标题"];
        return;
    }
    if (!self.info) {
        [QSAppKeyWindow showAutoHideHudWithText:@"请输入问题描述"];
        return;
    }
    sender.userInteractionEnabled = NO;
    [QSAppKeyWindow showIndeterminateHudWithText:@"正在提交"];
    if (self.imageArr.count) {
        [QSOSSUploadHelper asyncUploadFilesToOSS:self.imageArr complete:^(NSArray<NSString *> * _Nullable names, NSError * _Nullable error) {
            [QSAppKeyWindow hideHud];
            if (!error) {
                self.sendPicArr = names;
                [self addActionWithUrlArr:self.sendPicArr];
            }
        }];
    }else{
        [self addActionWithUrlArr:self.sendPicArr];
    }
}

- (void)addActionWithUrlArr:(NSArray <NSString *> *)urlArr{
    NSLog(@"%@", urlArr);
    for (int i = 0; i < urlArr.count; i++) {
        NSString *feedImage = urlArr[i];
        if (i == 0) {
            _pic = feedImage;
        } else {
            _pic = [NSString stringWithFormat:@"%@,%@",_pic,feedImage];
        }
    }
    [QSAppKeyWindow showIndeterminateHudWithText:@"正在提交"];
    [QSProblemReprotInterface postNewProblemWithTypeId:_typeId Title:_problemTitle Info:_info Pic:_pic CompanyKey:_companyKey AndBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        [QSAppKeyWindow hideHud];
        self.submitButton.userInteractionEnabled = YES;
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            if (self.signId) {//签到过来的直接返回首页
                [UIApplication sharedApplication].keyWindow.rootViewController = [[QSMainTabBarController alloc] init];
                [QSAppKeyWindow showAutoHideHudWithText:@"提交成功"];
            }else{
                [QSAppKeyWindow showAutoHideHudWithText:@"上传成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }];
}

- (void)handleBackHome:(UIBarButtonItem *)sender{
    [UIApplication sharedApplication].keyWindow.rootViewController = [[QSMainTabBarController alloc] init];
}
#pragma mark - **************** UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        QSProblemReportSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:problemSecoundcell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.companyName && self.companyKey && self.signId && self.townshipName) {
            //从签到成功页条转过来的直接赋值企业
            cell.selectEnterpriseLabel.text = self.companyName;
            cell.selectEnterpriseLabel.userInteractionEnabled = NO;
            
            cell.selectStreetLabel.text = self.townshipName;
            cell.selectStreetLabel.userInteractionEnabled = NO;
        }
        cell.didSelectCompanyFinishBlock = ^(NSString * _Nonnull companyKey) {
            NSLog(@"%@", companyKey);
            self.companyKey = companyKey;
        };
        
        if (_townArr.count) {
            cell.townArr = _townArr;
            cell.didSelectTownFinishBlock = ^(NSString * _Nonnull townId) {
                NSLog(@"%@", townId);
            };
        }
        return cell;
    }else{
        QSProblemReportFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:problemFirstcell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (_problemTypeArr.count) {
            cell.problemTypeArr = _problemTypeArr;
            cell.didSelectProblemTypeFinish = ^(NSString * _Nonnull ptName, NSString * _Nonnull ptId) {
                self.typeId = ptId;
            };
        }
        cell.didTitleInputFinish = ^(NSString * _Nonnull problemTitle) {
            NSLog(@"%@", problemTitle);
            self.problemTitle = problemTitle;
        };
        cell.didDescriptionInputFinish = ^(NSString * _Nonnull problemDescription) {
            NSLog(@"%@", problemDescription);
            self.info = problemDescription;
        };
        cell.didSelectImageFinish = ^(NSArray * _Nonnull imageArr) {
            NSLog(@"%@", imageArr);
            self.imageArr = imageArr;
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return kRealValue(92 + 2);//cell间距
    }else{
        return kRealValue(374 + 2);
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *headerLabel;
    if (section == 0) {
        headerLabel = [UILabel labelWithName:@"  企业信息" font:[UIFont QSFontOfSize15] textColor:[UIColor QSColorBlack434343] textAlignment:NSTextAlignmentLeft];
       
    }else{
         headerLabel = [UILabel labelWithName:@"  问题基础信息" font:[UIFont QSFontOfSize15] textColor:[UIColor QSColorBlack434343] textAlignment:NSTextAlignmentLeft];
    }
    headerLabel.backgroundColor = [UIColor clearColor];
    return headerLabel;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kRealValue(39);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
//去掉tableview的粘性 使header联动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.tableView)
    {
        CGFloat sectionHeaderHeight = 39;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

#pragma mark - Request
- (void)getProblemType{
    [QSProblemReprotInterface getApiProblemTypeListWithBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSArray * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            self.problemTypeArr = result;
            [self.tableView reloadData];
        }
    }];
}

- (void)getTownList{
    [QSProblemReprotInterface getApiTownListListWithBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            self.townArr = result[@"list"];
            [self.tableView reloadData];
        }
    }];
}

- (void)getCompanyList{
//    [QSProblemReprotInterface getApiCompanyListWithBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSArray * _Nonnull result) {
//        if (rspStatusAndMessage.code == kResponseSuccessCode) {
//            self.companyArr = result;
//            [self.tableView reloadData];
//        }
//    }];
    [QSProblemReprotInterface getApiCompanyListWithPageIndex:1 TownShipId:nil CompanyName:nil andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSProblemCompanyListModel * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            self.companyArr = result.list;
            [self.tableView reloadData];
        }
    }];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}
@end
